import {createRouter, createWebHistory} from 'vue-router'
import Login from '../components/Login.vue'
import RealtimeMonitor from '../components/RealtimeMonitor.vue'
import HistoryDataManagement from '../components/HistoryDataManagement.vue'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: {
            title: '登录 - OCR制证',
            requiresGuest: true
        }
    },
    {
        path: '/',
        name: 'Home',
        redirect: () => {
            // 根据登录状态决定重定向目标
            const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
            return isLoggedIn ? '/monitor' : '/login'
        }
    },
    {
        path: '/monitor',
        name: 'RealtimeMonitor',
        component: RealtimeMonitor,
        meta: {
            title: '实时监控 - OCR制证',
            requiresAuth: true
        }
    },
    {
        path: '/history',
        name: 'HistoryDataManagement',
        component: HistoryDataManagement,
        meta: {
            title: '历史数据管理 - OCR制证',
            requiresAuth: true
        }
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 检查登录状态
const isLoggedIn = () => {
    return localStorage.getItem('isLoggedIn') === 'true'
}

// 路由守卫
router.beforeEach((to, from, next) => {
    // 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title
    }

    const loggedIn = isLoggedIn()

    // 需要登录的页面
    if (to.meta.requiresAuth && !loggedIn) {
        next('/login')
        return
    }

    // 已登录用户访问登录页面，重定向到监控页面
    if (to.meta.requiresGuest && loggedIn) {
        next('/monitor')
        return
    }

    next()
})

export default router